//
//  TDatePickerView.m
//  TDatePicker
//
//  ITUIHelper
//
//  Created by txj on 2017/3/23.
//  Copyright © 2017年 hs. All rights reserved.
//

//

#import "TAddressPickerView.h"
#import <ITCategory/UIVIew+Extension.h>
#import "CitysHelper.h"
#import <ITCategory/PublicConfig.h>

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kPickerSize self.datePicker.frame.size
#define RGBA(r, g, b, a) ([UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:a])
#define RGB(r, g, b) RGBA(r,g,b,1)


#define MAXYEAR 2050
#define MINYEAR 1970

typedef void(^addressSelectDoneBlock)(NSString *provinceCode,NSString *cityCode,NSString *countyCode,NSString *province,NSString *city,NSString *county);

@interface TAddressPickerView ()<UIPickerViewDelegate,UIPickerViewDataSource,UIGestureRecognizerDelegate> {
    //日期存储数组
    NSArray *_provinceArray;
    NSArray *_cityArray;
    NSArray *_districtArray;
    
    //记录位置
    NSInteger _provinceIndex;
    NSInteger _cityIndex;
    NSInteger _districtIndex;
    
    NSInteger preRow;
}
@property (weak, nonatomic) IBOutlet UIView *buttomView;
@property (weak, nonatomic) IBOutlet UILabel *showYearView;
@property (weak, nonatomic) IBOutlet UIButton *doneBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;

- (IBAction)doneAction:(UIButton *)btn;


@property (nonatomic,strong)UIPickerView *addressPicker;
@property (nonatomic,strong)addressSelectDoneBlock addrSelectDoneBlock;


@end

@implementation TAddressPickerView

-(instancetype)initWithCompleteBlock:(void(^)(NSString *provinceCode,NSString *cityCode,NSString *countyCode,NSString *province,NSString *city,NSString *county))completeBlock{
    self = [super init];
    if (self) {
        self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] lastObject];
        
        [self setupUI];
        [self defaultConfig];
        
        if (completeBlock) {
            self.addrSelectDoneBlock = ^(NSString *provinceCode,NSString *cityCode,NSString *countyCode,NSString *province,NSString *city,NSString *county) {
                completeBlock(provinceCode,cityCode,countyCode,province,city,county);
            };
        }
    }
    return self;
}

-(void)setupUI {
    self.buttomView.layer.cornerRadius = 10;
    self.buttomView.layer.masksToBounds = YES;
    //self.themeColor = [UIColor colorFromHexRGB:@"#f7b639"];
    self.themeColor = [UIColor colorWithRed:25/255.0 green:149/255.0 blue:251/255.0 alpha:1/1.0];
;
    self.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    
    //点击背景是否影藏
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    self.bottomConstraint.constant = -self.height;
    self.backgroundColor = RGBA(0, 0, 0, 0);
    [self layoutIfNeeded];
    
   
    
    
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
    
    [self.showYearView addSubview:self.addressPicker];
    
}

-(void)defaultConfig {
  
    //设置省市县数据
    _provinceArray = [CitysHelper selectCitysWithConditions: @"LEVELTYPE = 1"];
    if (_provinceArray.count > 0) {
        _cityArray =[self getCityArray:[[_provinceArray objectAtIndex:0] objectForKey: @"id"]];
    }
    if (_cityArray.count > 0) {
        _districtArray =[self getDistrictArray:[[_cityArray objectAtIndex:0] objectForKey: @"id"]];
    }
}


- (NSMutableArray *)setArray:(id)mutableArray
{
    if (mutableArray)
        [mutableArray removeAllObjects];
    else
        mutableArray = [NSMutableArray array];
    return mutableArray;
}

-(void)setAreasByAreaCode:(NSString *)areacode withAreaType:(TAreaType)areaType
{
    if (areaType==TAreaTypeProvence) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat: @"id  == %@",[NSString stringWithFormat:@"%@0000",[areacode substringWithRange:NSMakeRange(0, 2)]]];
        NSDictionary *dic=[[_provinceArray filteredArrayUsingPredicate:predicate] objectAtIndex:0];
        _provinceIndex=[_provinceArray indexOfObject:dic];
        _cityArray =[self getCityArray:[[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"id"]];
        if ([_cityArray count]>0) {
            _districtArray=[self getDistrictArray:[[_cityArray objectAtIndex:0] objectForKey: @"id"]];
        }
        else{
            _districtArray=@[];
        }
    }
    else if(areaType==TAreaTypeCity)
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat: @"id  == %@",[NSString stringWithFormat:@"%@0000",[areacode substringWithRange:NSMakeRange(0, 2)]]];
        NSDictionary *dic=[[_provinceArray filteredArrayUsingPredicate:predicate] objectAtIndex:0];
        _provinceIndex=[_provinceArray indexOfObject:dic];
        
        _cityArray =[self getCityArray:[[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"id"]];
        
        if ([_cityArray count]>0) {
            
            NSPredicate *predicate2 = [NSPredicate predicateWithFormat: @"id  == %@",[NSString stringWithFormat:@"%@00",[areacode substringWithRange:NSMakeRange(0, 4)]]];
            NSDictionary *dic2=[[_cityArray filteredArrayUsingPredicate:predicate2] objectAtIndex:0];
            _cityIndex=[_cityArray indexOfObject:dic2];
            
            _districtArray=[self getDistrictArray:[[_cityArray objectAtIndex:_cityIndex] objectForKey: @"id"]];
        }
        else{
            _districtArray=@[];
        }
    }
    else if(areaType==TAreaTypeDistrict)
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat: @"id  == %@",[NSString stringWithFormat:@"%@0000",[areacode substringWithRange:NSMakeRange(0, 2)]]];
        NSDictionary *dic=[[_provinceArray filteredArrayUsingPredicate:predicate] objectAtIndex:0];
        _provinceIndex=[_provinceArray indexOfObject:dic];
        
        _cityArray =[self getCityArray:[[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"id"]];
        
        if ([_cityArray count]>0) {
            
            NSPredicate *predicate2 = [NSPredicate predicateWithFormat: @"id  == %@",[NSString stringWithFormat:@"%@00",[areacode substringWithRange:NSMakeRange(0, 4)]]];
            NSDictionary *dic2=[[_cityArray filteredArrayUsingPredicate:predicate2] objectAtIndex:0];
            _cityIndex=[_cityArray indexOfObject:dic2];
            
            _districtArray=[self getDistrictArray:[[_cityArray objectAtIndex:_cityIndex] objectForKey: @"id"]];
            
            NSPredicate *predicate3 = [NSPredicate predicateWithFormat: @"id  == %@",areacode];
            NSDictionary *dic3=[[_districtArray filteredArrayUsingPredicate:predicate3] objectAtIndex:0];
            _districtIndex=[_districtArray indexOfObject:dic3];
        }
        else{
            _districtArray=@[];
        }

    }
    
    switch (self.addressPickerStyle) {
        case TAddressStyleShowProvence:
            [self.addressPicker selectRow:_provinceIndex inComponent:0 animated:YES];
            break;
        case TAddressStyleShowProvenceCity:
            [self.addressPicker selectRow:_provinceIndex inComponent:0 animated:YES];
            [self.addressPicker selectRow:_cityIndex inComponent:1 animated:YES];
            break;
        case TAddressStyleShowProvenceCityDistrict:
            [self.addressPicker selectRow:_provinceIndex inComponent:0 animated:YES];
            [self.addressPicker selectRow:_cityIndex inComponent:1 animated:YES];
            [self.addressPicker selectRow:_districtIndex inComponent:2 animated:YES];
            break;
    }

    
   
    
    
//
//    _cityArray =[self getCityArray:[[_provinceArray objectAtIndex:[_provinceArray count]-1] objectForKey: @"id"]];
//    if ([_cityArray count]>0) {
//        _districtArray=[self getDistrictArray:[[_cityArray objectAtIndex:0] objectForKey: @"id"]];
//    }
//    else{
//        _districtArray=@[];
//    }

}

#pragma mark - UIPickerViewDelegate,UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    switch (self.addressPickerStyle) {
        case TAddressStyleShowProvence:
            return 1;
        case TAddressStyleShowProvenceCity:
            return 2;
        case TAddressStyleShowProvenceCityDistrict:
            return 3;
        default:
            return 0;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    NSArray *numberArr = [self getNumberOfRowsInComponent];
    return [numberArr[component] integerValue];
}

-(NSArray *)getNumberOfRowsInComponent {
    
    NSInteger pNum = _provinceArray.count;
    NSInteger cNum = _cityArray.count;
    NSInteger dNum = _districtArray.count;    
    
    switch (self.addressPickerStyle) {
        case TAddressStyleShowProvence:
            return @[@(pNum)];
            break;
        case TAddressStyleShowProvenceCity:
            return @[@(pNum),@(cNum)];
            break;
        case TAddressStyleShowProvenceCityDistrict:
            return @[@(pNum),@(cNum),@(dNum)];
            break;
        default:
            return @[];
            break;
    }
    
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}


-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *customLabel = (UILabel *)view;
    if (!customLabel) {
        customLabel = [[UILabel alloc] init];
        customLabel.textAlignment = NSTextAlignmentCenter;
        [customLabel setFont:[UIFont systemFontOfSize:17]];
    }
    NSString *title;
    
    switch (self.addressPickerStyle) {
        case TAddressStyleShowProvence:
            if (component==0) {
                title = [_provinceArray[row] objectForKey:@"name"];
            }
            break;
        case TAddressStyleShowProvenceCity:
            if (component==0) {
                title = [_provinceArray[row] objectForKey:@"name"];
            }
            if (component==1) {
                title = [_cityArray[row] objectForKey:@"name"];
            }
            break;
        case TAddressStyleShowProvenceCityDistrict:
            if (component==0) {
                title = [_provinceArray[row] objectForKey:@"name"];
            }
            if (component==1) {
                title = [_cityArray[row] objectForKey:@"name"];
            }
            if (component==2) {
                title = [_districtArray[row] objectForKey:@"name"];
            }
            break;
        default:
            title = @"";
            break;
    }

    customLabel.text = title;
    customLabel.textColor = [UIColor blackColor];
    return customLabel;
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (self.addressPickerStyle) {
        case TAddressStyleShowProvence:{
            
            if (component == 0) {
                _provinceIndex = row;
                
//                self.showYearView.text =[_provinceArray[_provinceIndex] objectForKey:@"name"];
            }
        }
            break;
            
            
        case TAddressStyleShowProvenceCity:{
            
            if (component == 0) {
                _provinceIndex = row;
                _cityArray =[self getCityArray:[[_provinceArray objectAtIndex:row] objectForKey: @"id"]];
//                self.showYearView.text =[_provinceArray[_provinceIndex] objectForKey:@"name"];
            }
            if (component == 1) {
                _cityIndex = row;
            }
            
        }
            break;
            
            
        case TAddressStyleShowProvenceCityDistrict:{
            
            
            if (component == 0) {
                _provinceIndex = row;
                _cityArray =[self getCityArray:[[_provinceArray objectAtIndex:row] objectForKey: @"id"]];
                if ([_cityArray count]>0) {
                     _districtArray=[self getDistrictArray:[[_cityArray objectAtIndex:0] objectForKey: @"id"]];
                }
                else{
                    _districtArray=@[];
                }
               
//                self.showYearView.text =[_provinceArray[_provinceIndex] objectForKey:@"name"];
            }
            if (component == 1) {
                _cityIndex = row;
                if ([_cityArray count]>0) {
                    _districtArray=[self getDistrictArray:[[_cityArray objectAtIndex:row] objectForKey: @"id"]];
                }
                else{
                    _districtArray=@[];
                }

            }
            if (component == 2) {
                _districtIndex = row;
            }
            
        }
            break;
            
        default:
            break;
    }
    
    [pickerView reloadAllComponents];
}


#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if( [touch.view isDescendantOfView:self.buttomView]) {
        return NO;
    }
    return YES;
}



#pragma mark - Action
-(void)show {
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:.3 animations:^{
        self.bottomConstraint.constant = 0;
        self.backgroundColor = RGBA(0, 0, 0, 0.4);
        [self layoutIfNeeded];
    }];
}
-(void)dismiss {
    [UIView animateWithDuration:.3 animations:^{
        self.bottomConstraint.constant = -self.height;
        self.backgroundColor = RGBA(0, 0, 0, 0);
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self removeFromSuperview];
    }];
}

- (IBAction)doneAction:(UIButton *)btn {
    switch (self.addressPickerStyle) {
        case TAddressStyleShowProvence:{
            self.addrSelectDoneBlock(
                                     [[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"id"],
                                     @"",
                                     @"",
                                     [[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"name"],
                                     @"",
                                     @"");
        }
            break;
            
            
        case TAddressStyleShowProvenceCity:{
            self.addrSelectDoneBlock(
                                     [[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"id"],
                                     [[_cityArray objectAtIndex:_cityIndex] objectForKey: @"id"],
                                    @"",
                                     [[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"name"],
                                     [[_cityArray objectAtIndex:_cityIndex] objectForKey: @"name"],
                                     @"");
        }
            break;
            
            
        case TAddressStyleShowProvenceCityDistrict:{
            self.addrSelectDoneBlock(
                                     [[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"id"],
                                     [[_cityArray objectAtIndex:_cityIndex] objectForKey: @"id"],
                                     [[_districtArray objectAtIndex:_districtIndex] objectForKey: @"id"],
                                     [[_provinceArray objectAtIndex:_provinceIndex] objectForKey: @"name"],
                                     [[_cityArray objectAtIndex:_cityIndex] objectForKey: @"name"],
                                     [[_districtArray objectAtIndex:_districtIndex] objectForKey: @"name"]);
        }
            break;
            
        default:
            break;
    }
    
    
    [self dismiss];
}

#pragma mark - tools
//通过省编码获取市编码
-(NSArray *)getCityArray:(NSString *)areaCode
{
    return [CitysHelper selectCitysWithConditions: [NSString stringWithFormat: @"LEVELTYPE = 2 AND PARENTID = %@",areaCode]];
}
//通过省编码获取市编码
-(NSArray *)getDistrictArray:(NSString *)areaCode
{
      return [CitysHelper selectCitysWithConditions: [NSString stringWithFormat: @"LEVELTYPE = 3 AND PARENTID = %@",areaCode]];
}



#pragma mark - getter / setter
-(UIPickerView *)addressPicker {
    if (!_addressPicker) {
        [self.showYearView layoutIfNeeded];
        _addressPicker = [[UIPickerView alloc] initWithFrame:self.showYearView.bounds];
        _addressPicker.showsSelectionIndicator = YES;
        _addressPicker.delegate = self;
        _addressPicker.dataSource = self;
    }
    return _addressPicker;
}
-(void)setThemeColor:(UIColor *)themeColor {
    _themeColor = themeColor;
    self.doneBtn.backgroundColor = themeColor;
}
@end
